package com.bluexmicro.module_componment.scan

import android.app.Activity
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.bluexmicro.module_componment.databinding.ActivityInnerChooseDeviceBinding
import com.bluexmicro.module_componment.singleTap
import kotlinx.coroutines.launch

class ChooseDeviceActivity : AppCompatActivity() {

    private lateinit var binding: ActivityInnerChooseDeviceBinding

    private val viewModel by viewModels<ScanViewModel> {
        ScanViewModelFactory(application)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityInnerChooseDeviceBinding.inflate(layoutInflater)
        setContentView(binding.root)

        actionBar?.hide()
        supportActionBar?.hide()

        binding.backBtn.singleTap {
            finish()
        }

        lifecycleScope.launch {
            viewModel.selectedDevice.collect {
                val intent = Intent()
                intent.putExtra("ScanResult", it)
                setResult(Activity.RESULT_OK, intent)
                finish()
            }
        }

    }

    companion object {

        //只能在onCreate中初始化
        fun getActivityResultContract(): ChooseTargetDevice {
            return ChooseTargetDevice()
        }

    }
}

class ChooseTargetDevice : ActivityResultContract<Int, ScanResult?>() {

    override fun createIntent(context: Context, input: Int?): Intent {
        val intent = Intent(context, ChooseDeviceActivity::class.java)
        intent.putExtra("requestCode", input ?: 0)
        return intent
    }


    override fun parseResult(resultCode: Int, intent: Intent?): ScanResult? {
        return if (resultCode == Activity.RESULT_OK) {
            intent?.getParcelableExtra("ScanResult") as ScanResult?
        } else {
            null
        }
    }


}